package com.itheima.bakery.demos.web.controller;

import com.itheima.bakery.demos.web.model.Inventory;
import com.itheima.bakery.demos.web.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/inventory")
public class InventoryController {
    @Autowired
    private InventoryService inventoryService;

    @GetMapping
    public List<Inventory> listInventory() {
        return inventoryService.findAllInventory();
    }

    @PostMapping
    public Inventory createInventory(@RequestBody Inventory inventory) {
        return inventoryService.saveInventory(inventory);
    }

    @GetMapping("/{productID}")
    public ResponseEntity<Inventory> getInventoryByProductID(@PathVariable Integer productID) {
        return inventoryService.findInventoryByProductID(productID)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{productID}")
    public ResponseEntity<Inventory> updateInventory(@PathVariable Integer productID, @RequestBody Inventory inventory) {
        inventory.setProductID(productID);
        Inventory updatedInventory = inventoryService.saveInventory(inventory);
        return ResponseEntity.ok(updatedInventory);
    }

    @DeleteMapping("/{productID}")
    public ResponseEntity<Void> deleteInventory(@PathVariable Integer productID) {
        inventoryService.deleteInventory(productID);
        return ResponseEntity.ok().build();
    }
}